# encoding=utf8
import datetime
from django import forms
from django.contrib.auth import *
from django.contrib.auth.models import *
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db import transaction
from django.db.models import F
from django.db.models.query_utils import Q
from django.forms.forms import Form
from django.forms.models import model_to_dict
from django.http import *
from django.shortcuts import *
import json

from trp.models import *
from utils.JsonResponse import JsonResponse, JsonResponseBadrequest
from utils.decorators import *
from utils.utils import *
from website.settings import LOGGER as logger
from trp.views.strategy import get_default_traffic_strategy,get_strategy_price
from django.db import transaction
from trp.views.costlog import get_cost_by_traffic
MAX_INT=2147483647

@login_required
def main(request):
    # 进行权限控制，目前有1：流量采购&管理2：平台流量使用者3：商铺&供应商流量使用者
    position_id = request.GET.get("position_id")
    account = request.user.account
    if account.is_admin():
        return traffic_response(request,'trp/traffic_admin.html',{'position_id':position_id})
    elif account.is_platform_user():
        return traffic_response(request,'trp/traffic_platform.html',{'position_id':position_id})
    elif account.is_vendor_user() or account.is_merchant_user():
        return traffic_response(request,'trp/traffic_merchant.html',{'position_id':position_id})

@login_required_ajax
def get_list(request):
    # 进行权限控制，目前有1：流量采购&管理2：平台流量使用者3：商铺&供应商流量使用者
    account = request.user.account
    if account.is_admin():
        return get_admin_list(request)
    elif account.is_platform_user():
        return get_platform_list(request)
    elif account.is_vendor_user() or account.is_merchant_user():
        return get_merchant_list(request)


# traffic table , search can be use
def  get_admin_list(request):
    params = json.loads(request.body)
    search_text = params.get("search_text", "").strip()  # 模糊搜索
    position_id=params.get("position_id")
    start = params.get("start")
    end = params.get("end")
    height = params.get("height")
    width = params.get("width")
    order_by = params.get("orderBy","id")
    order= params.get("order","desc")
    if order_by :
        order_by = (order =="asc" and "" or "-") + order_by
    pageSize = int(params.get("pageSize", 30))
    pageNo = int(params.get("pageNo", 1))

    args = []  # 模糊查询条件
    kwargs = {}  # 动态查询条件
    order_arr = []  # 排序
    if width and height :
        kwargs["position__width"]=int(width)
        kwargs["position__height"]=int(height)
    if position_id:
        kwargs["position_id"]=int(position_id)
    kwargs['deleted'] = False
    # 多字段查找
#     if search_text:
#         args.append(((Q(position__name__icontains=search_text) or Q(position__attrs__name__icontains=search_text))))
#         if  search_text.isdigit():
#             size = int(search_text)
#             args.append((Q(position__width=size) | Q(position__height=size)))
#         else :
#         args.append()
#                    Q(position__media__name__icontains=search_text) |
#                    Q(position__media__attrs__name__icontains=search_text)
                   
    # 排序
    
    if order_by:
        order_arr.append(order_by)
    lst = Traffic.objects.prefetch_related("position__attrs","TRAFFIC","position__media__attrs").select_related().filter(**kwargs)
    
    if start and end :
        lst = lst.filter(Q(start__range=(start,end)) | Q(end__range=(start,end))|Q(start__lte=start,end__gte=end)|Q(start__gte=start,end__lte=end))
    if search_text :
        lst = lst.filter(
                         Q(position__name__icontains=search_text) |
                         Q(position__attrs__name__icontains=search_text) |
                         Q(position__media__name__icontains=search_text) |
                         Q(position__media__attrs__name__icontains=search_text),
                         Q(deleted=False)).order_by(*order_arr).distinct()
    else :
        lst = lst.filter(Q(deleted=False)).order_by(*order_arr).distinct()
        
    return get_paged_result(lst,ListType.admin,pageNo,pageSize)
def  get_platform_list(request):
    params = json.loads(request.body)
    search_text = params.get("search_text", "").strip()  # 模糊搜索
    position_id=params.get("position_id")
    start = params.get("start")
    end = params.get("end")
    height = params.get("height")
    width = params.get("width")
    order_by = params.get("orderBy", "id")
    order= params.get("order","desc")
    if order_by :
        order_by = (order =="asc" and "" or "-") + order_by
    pageSize = int(params.get("pageSize", 30))
    pageNo = int(params.get("pageNo", 1))

    args = []  # 模糊查询条件
    kwargs = {}  # 动态查询条件
    order_arr = []  # 排序
    kwargs['deleted'] = False
    kwargs['active'] = True
    if width and height :
        kwargs["position__width"]=int(width)
        kwargs["position__height"]=int(height)
    kwargs["end__gte"]=today()
    if position_id:
        kwargs["position_id"]=int(position_id)
    # 多字段查找
#     if search_text:
#         if  search_text.isdigit():
#             size = int(search_text)
#             args.append((Q(position__width=size) | Q(position__height=size)))
#         args.append(
#                    Q(position__name__icontains=search_text) |
#                    Q(position__attrs__name__icontains=search_text) |
#                    Q(position__media__name__icontains=search_text) |
#                    Q(position__media__attrs__name__icontains=search_text)
#                    )
    # 排序
    if order_by:
        order_arr.append(order_by)
    lst = Traffic.objects.prefetch_related("position__attrs","TRAFFIC","position__media__attrs").select_related().filter(**kwargs)
    if start and end :
        lst = lst.filter(Q(start__range=(start,end)) | Q(end__range=(start,end))|Q(start__lte=start,end__gte=end)|Q(start__gte=start,end__lte=end))
    if search_text :
        lst = lst.filter(
                   Q(position__name__icontains=search_text) |
                   Q(position__attrs__name__icontains=search_text) |
                   Q(position__media__name__icontains=search_text) |
                   Q(position__media__attrs__name__icontains=search_text),
                   Q(deleted=False)).order_by(*order_arr).distinct()
    else :
        lst = lst.filter(Q(deleted=False)).order_by(*order_arr).distinct()
    return get_paged_result(lst,ListType.flat,pageNo,pageSize)
def  get_merchant_list(request):
    params = json.loads(request.body)
    search_text = params.get("search_text", "").strip()  # 模糊搜索
    position_id=params.get("position_id")
    start = params.get("start")
    end = params.get("end")
    height = params.get("height")
    width = params.get("width")
    order_by = params.get("orderBy", "id")
    order= params.get("order","desc")
    if order_by :
        order_by = (order =="asc" and "" or "-") + order_by
    pageSize = int(params.get("pageSize", 30))
    pageNo = int(params.get("pageNo", 1))

    args = []  # 模糊查询条件
    kwargs = {}  # 动态查询条件
    order_arr = []  # 排序
    kwargs['deleted'] = False
    kwargs['active'] = True
    if width and height :
        kwargs["position__width"]=int(width)
        kwargs["position__height"]=int(height)
    kwargs["end__gte"]=today()
    #kwargs["TRAFFIC__allow_shared"]=True
    if position_id:
        kwargs["position_id"]=int(position_id)
    # 排序
    if order_by:
        order_arr.append(order_by)
    org = request.user.account.get_organization()  
    traffic_ids=Resource.objects.filter(Q(deleted=False),Q(is_default=True,allow_shared=True)|Q(is_default=False,RESOURCE__organization=org)).distinct().values_list('traffic_id', flat=True)
    if traffic_ids:
        kwargs["id__in"]=traffic_ids
    lst = Traffic.objects.prefetch_related("position__attrs","TRAFFIC","position__media__attrs").select_related().filter(**kwargs)
    if start and end :
        lst = lst.filter(Q(start__range=(start,end)) | Q(end__range=(start,end))|Q(start__lte=start,end__gte=end)|Q(start__gte=start,end__lte=end))
    if search_text :
        lst = lst.filter(
                   Q(position__name__icontains=search_text) |
                   Q(position__attrs__name__icontains=search_text) |
                   Q(position__media__name__icontains=search_text) |
                   Q(position__media__attrs__name__icontains=search_text),
                   Q(deleted=False)).order_by(*order_arr).distinct()
    else :
        lst = lst.filter(Q(deleted=False)).order_by(*order_arr).distinct()
    return get_paged_result(lst,ListType.shop,pageNo,pageSize)
#分页后的json数据
def get_paged_result(list,list_type,pageNo,pageSize):
    paginator = Paginator(list, pageSize)
    try:
        pageObj = paginator.page(pageNo)
    except PageNotAnInteger:
        pageObj = paginator.page(1)
    except EmptyPage:
        pageObj = paginator.page(paginator.num_pages)
    results = {}
    datalist =None
    if list_type==ListType.admin:
        datalist = traffic_admin_to_json(pageObj.object_list)
    elif list_type==ListType.flat:
        datalist = traffic_platform_to_json(pageObj.object_list)
    elif list_type==ListType.shop:
        datalist = traffic_shop_to_json(pageObj.object_list)
    results['bodyData'] = datalist

    results["pageNo"]=pageNo
    results["pageSize"]=pageSize
    results["totalCount"]=paginator.count
    results["time"]=datetime.datetime.now().strftime("%Y-%m-%d")
    return JsonResponse(results)

#打开要修改的广告位流量dialog
@login_required_ajax
def get_one(request):
    params = request.GET
    traffic_detail = {}
    try:
        id = params.get("traffic_id")
        traffic = Traffic.objects.select_related("position").get(id=int(id))
        position = traffic.position
        traffic_detail['position_id']=position.id
        traffic_detail['position_name'] = position.name
        traffic_detail['position_attrs']=position_attrs_to_str(position.attrs.all())
        traffic_detail['mertial_type'] = join_to_str(position.types.all(),'name','/')
        if position.size ==MAX_INT :
            traffic_detail["size"]="--"
        else :
            traffic_detail["size"]=position.size/1024
        traffic_detail['start'] =traffic.start
        traffic_detail['end'] =traffic.end
        traffic_detail['position_max']=traffic.position.max
        traffic_detail['bid_type'] = traffic.bid_type
        traffic_detail['bid_price'] = traffic.bid_price
        traffic_detail['pv'] = traffic.estimated_imp
        traffic_detail['click'] = traffic.estimated_click
        resources = Resource.objects.filter(traffic=traffic,allow_shared=True)
        if not resources:
            traffic_detail['shared'] = 0
            traffic_detail['floor'] = 0
        else:
            resource=resources[0]            
            traffic_detail['shared'] = 1
            traffic_detail['floor'] = resource.floor
                
            
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({"message":str(e)})
    return JsonResponse(traffic_detail)
#traffic 报表，使用当前广告位的
@login_required_ajax
def get_report(request):
    account = request.user.account
    params = request.GET
    result = {}
    try:
        id = params.get("traffic_id")
        start_select = params.get('start')
        end_select = params.get('end')
        traffic = Traffic.objects.get(id=int(id))
        position = traffic.position
        #时间段在流量开始时间到当前时间的前一天
        start = traffic.start
        end = yestoday()
        if start_select or start_select !='':
            start = datetime.datetime.strptime(start_select,"%Y-%m-%d").date()
        if end_select or end_select !='':
            end = datetime.datetime.strptime(end_select,"%Y-%m-%d").date()
        kwargs = {}  # 动态查询条件
        kwargs['date__gte']= start
        kwargs['date__lte'] = end
        kwargs['position'] = position
        role = None
        position_reports=None
        if account.is_admin():
            position_reports = DailyPositionReport.objects.filter(**kwargs).order_by("-date")
            role = 1
        elif account.is_platform_user():
            position_reports = DailyPositionReport.objects.filter(**kwargs).order_by("-date")
            role =2
        elif account.is_vendor_user() or account.is_merchant_user():
            kwargs["organization__in"]=request.user.account.organization.all()
            position_reports = DailyOrganizationPositionReport.objects.filter(**kwargs).order_by("-date")
            role = 3
        datalist = traffic_reports_to_json(position_reports,traffic,role,start,end)
        result['data'] = datalist
    except Exception,e:
        logger.exception(e)
    return  JsonResponse(result)

#新建广告位流量
@login_required_ajax
@transaction.commit_manually
def  do_create(request):
     params = json.loads(request.body)
     position_id = int(params.get('position_id',-1))
     start = params.get('start')
     end = params.get('end')
     bid_type = int(params.get('bid_type'))
     bid_price = params.get('bid_price')
     imp = params.get('estimated_imp') or 0
     click = params.get('estimated_click') or 0
     floor = params.get('floor',0)or 0
     allow_shared = int(params.get('shared',0))
     shared=False
     if allow_shared==1:
         shared=True
     else :
         floor=0  
         shared=False
     try:
         position = Position.objects.get(id=int(position_id))#必须有这个广告位
         is_exists = position.traffic_set.all().filter(Q(deleted=False),
                                                   Q(start__range=(start,end))|Q(end__range=(start,end))
                                                   ).exists()
         if is_exists:
             raise Exception("date.illegal") 
         #新建流量
         traffic = Traffic()
         position = Position.objects.get(id=position_id)#必须有这个广告位
         traffic.position = position
         traffic.name = ""
         traffic.start = start
         traffic.end = end
         traffic.bid_type = bid_type
         traffic.bid_price = bid_price
         traffic.estimated_imp =imp
         traffic.estimated_click =click
         traffic.save()
         #新建默认分片
         resource = Resource()
         resource.name = ""
         resource.start = traffic.start
         resource.end = traffic.end
         resource.floor = floor
         resource.traffic = traffic
         resource.allow_shared=shared
         resource.is_default=True
         resource.save()
         #设置默认策略 
         strategy = Strategy().default_strategy()
         strategy.start = traffic.start
         strategy.end = traffic.end
         strategy.organization = request.user.account.get_organization()
         strategy.save()
         #将可竞价的分片与默认策略绑定
         resource_price = ResourcePrice()
         resource_price.resource = resource
         resource_price.strategy = strategy
         resource_price.price = 0
         resource_price.save()
         #allocation
         if not shared:
             allocation = Allocation()
             allocation.start = resource.start
             allocation.end = resource.end
             allocation.type = traffic.bid_type
             allocation.price = traffic.bid_price
             allocation.amount =0
             allocation.priority = 0
             allocation.resource = resource
             org = Organization.objects.filter(type=0)[0]
             allocation.organization=org
             allocation.save()     
     except Exception,ex:
         transaction.rollback()
         logger.exception(ex)
         return JsonResponseBadrequest({})
     else:
         transaction.commit()
     return JsonResponse({})

@login_required_ajax
@transaction.commit_manually
def do_update(request):
    params = json.loads(request.body)
    traffic_id = int(params.get('traffic_id',0))    
    start = params.get('start')
    end = params.get('end')
    bid_type = int(params.get('bid_type'))
    bid_price = float(params.get('bid_price',0))
    imp = int(params.get('estimated_imp') or 0)
    click = int(params.get('estimated_click') or 0)
    floor = float(params.get('floor',0)or 0)
    allow_shared = int(params.get('shared',0))
    shared=False
    if allow_shared==1:
        shared=True
    else :
        floor=0
        shared=False
    try:
        traffic = Traffic.objects.get(pk=traffic_id)
        position = traffic.position#必须有这个广告位
        is_exists = position.traffic_set.all().filter(Q(deleted=False),
                                                   Q(start__range=(start,end))|Q(end__range=(start,end))
                                                   ).exclude(id=traffic_id).exists()
        if is_exists:
             raise Exception("date.illegal") 
        
        if not can_traffic_update(traffic_id,start,end):
            return JsonResponseBadrequest({"message":"流量中存在不属于该日期范围内的分片!"})
        #修改流量
        traffic.start = start
        traffic.end = end
        traffic.bid_type = bid_type
        traffic.bid_price = bid_price
        traffic.estimated_imp =imp
        traffic.estimated_click =click
        traffic.save()
        #修改默认分片
        default_resource=Resource.objects.get(traffic_id=traffic_id,is_default=True)    
        old_shared=default_resource.allow_shared
        old_floor=default_resource.floor
        if old_shared != shared:
            if shared:
                default_resource.RESOURCE.all().delete()               
                rps=ResourcePrice.objects.filter(resource=default_resource,strategy__priority=20)
                for rp in rps:
                    strategy=rp.strategy
                    strategy_price=get_strategy_price(strategy)
                    rp.price=strategy_price+floor
                    rp.save()                    
            else:
                allocation = Allocation()
                allocation.start = start
                allocation.end = end
                allocation.type = bid_type
                allocation.price =bid_price
                allocation.amount =0
                allocation.priority = 0
                allocation.resource = default_resource
                org = Organization.objects.filter(type=0)[0]
                allocation.organization=org
                allocation.save()  
                ResourcePrice.objects.filter(resource=default_resource).update(price=0)    
        else:
            if shared:
                price=floor-old_floor
                ResourcePrice.objects.filter(resource=default_resource,strategy__priority=20).update(price=F('price')+price)          
        
        default_resource.start = start
        default_resource.end = end
        default_resource.floor = floor
        default_resource.allow_shared=shared        
        default_resource.save()
        objs=ResourcePrice.objects.filter(resource=default_resource)
        default_strategy=get_default_traffic_strategy({"tid":traffic_id})
        if default_strategy:
            default_strategy.start=start
            default_strategy.end=end
            default_strategy.save()
        for obj in objs:
            obj.strategy.save()                              
    except Exception,ex:
         transaction.rollback()
         logger.exception(ex)
         return JsonResponseBadrequest({"message":str(ex)})
    else:
        transaction.commit()
    return JsonResponse({})
     
def can_traffic_update(traffic_id,start,end):
    tag=True
    if Resource.objects.filter(Q(is_default=False),Q(traffic_id=traffic_id),Q(start__lt=start)|Q(end__gt=end)).exists():
        tag=False
    return tag
         
    
    

@login_required_ajax
@transaction.commit_manually
def  do_delete(request):
    params =request.GET
    message ={}
    try:
        id = params.get("traffic_id")
        traffic = Traffic.objects.get(id=int(id))
        start = traffic.start
        is_start = False
        now = datetime.datetime.now()
        today = datetime.datetime(now.year,now.month,now.day)
        if start<=today.date():
            is_start = True
        if is_start:            
            traffic.end = today
            #检索流量所有未结束的分片结果集
            qset=traffic.TRAFFIC.prefetch_related("RESOURCE").filter(deleted=False,is_default=False,end__gt=today)
            for obj in qset:
                rid=obj.id
                old_start=obj.start
                old_end=obj.end
                old_allocation=obj.RESOURCE.all()[0]
                old_org_id=old_allocation.organization_id
                old_cost=old_allocation.price
                               
                if old_start > today.date(): #未开始的分片，全额退回
                    rest_cost=old_cost
                    new_cost=0
                    obj.deleted=True
                    obj.save()
                    CostLog.objects.filter(resource_id=rid).update(deleted=True)
                    obj.RESOURCE.all().delete()
                    obj.set_resource_area([])
                    obj.set_resource_hour([])
                    obj.resourceprice_set.all().delete()
                else:#已开始的分片
                    days=(today.date()-old_start).days+1
                    total_days=(old_end-old_start).days+1
                    new_cost=(old_cost/float(total_days))*days                    
                    cost_log=CostLog.objects.get(resource_id=rid)
                    cost_log.balance=new_cost
                    cost_log.time=now                   
                    cost_log.account=request.user.account
                    cost_log.save()    
                    old_allocation.price=new_cost
                    old_allocation.end=today
                    old_allocation.save()
 
            traffic.TRAFFIC.filter(deleted=False,end__gt=today,start__lte=today).update(end=today)
            #traffic.TRAFFIC.filter(deleted=False,end__gt=today,start__gt=today).update(deleted=True)
            traffic.save()
            operation_log=OperationLog()
            operation_log.operation="停止"
            operation_log.object="流量"
            operation_log.user=request.user
            operation_log.object_id=int(id)
            operation_log.save()
        else:#未开始的流量，根据独占分片返回账户余额,删除所有的分片以及消费记录
            #qset=traffic.TRAFFIC.prefetch_related("RESOURCE").filter(deleted=False,allow_shared=False,is_default=False)
            CostLog.objects.filter(resource__traffic=traffic).update(deleted=True)
            Allocation.objects.filter(resource__traffic=traffic).delete()
            ResourceArea.objects.filter(resource__traffic=traffic).delete()
            ResourceHour.objects.filter(resource__traffic=traffic).delete()
            ResourcePrice.objects.filter(resource__traffic=traffic).delete()
            traffic.TRAFFIC.update(deleted=True)
            traffic.deleted=True
            traffic.save()
            operation_log=OperationLog()
            operation_log.operation="删除"
            operation_log.object="流量"
            operation_log.user=request.user
            operation_log.object_id=int(id)
            operation_log.save()
    except Exception,e:
        transaction.rollback()
        message['result'] = "delete fail"
        message['message'] = "删除失败"
        logger.exception(e)
        return JsonResponseBadrequest(message)
    else:
        transaction.commit()
    return JsonResponse(message)

#流量开关
@login_required_ajax
@transaction.commit_manually
def do_on_off(request):
    params = request.POST
    message = AjaxResponse()
    try:
        id = params.get("traffic_id")
        active = params.get("active")
        activeInt = int(active)
        traffic = Traffic.objects.get(id=int(id))
        if activeInt==1:
            traffic.active = True
            details="开"
        else:
            traffic.active = False
            details="关"
        traffic.save()
        operation_log=OperationLog()
        operation_log.operation="开关"
        operation_log.object="流量"
        operation_log.user=request.user
        operation_log.details=details      
        operation_log.object_id=int(id) 
        operation_log.save()        
    except Exception,e:
        transaction.rollback()
        message.code = 300
        message.message = "失败"
        logger.exception(e)
        return JsonResponseBadrequest(message.to_dict())
    else:
        transaction.commit()
    return JsonResponse(message.to_dict())
#---------------------------------------------------utils---------------------------------------------------------------------------#
def traffic_response(request,html,dic):
    return render_to_response(html, dict({'user' : request.user, 'page' : 'traffic'},**dic))

class ListType:
        admin = 0
        flat = 1
        shop =2
def position_size_to_str(width, height):
    return "x".join([str(width), str(height)])
# 广告位属性列表转换为字符串
def position_attrs_to_str(attrs):
    return join_to_str(attrs,'name',',')
# 媒体属性列表转换为字符串
def media_attrs_to_str(attrs):
    return join_to_str(attrs,'name',',')
# 购买方式
def  traffic_bid_type(type):
    if type:
        return "CPM"
    else:
        return "CPD"
# 分配给平台还是竞价
def traffic_shared(shared):
    if shared:
        return "竞价"
    else:
        return "平台"
# 是否共享
def  traffic_oneself(shared):
    if shared:
        return "是"
    else:
        return "否"
# traffic 列表构造json,流量采购和管理者结果
def traffic_admin_to_json(list):
    datalist = []
    for traffic in list:
        data = {}
        data['traffic_id'] = traffic.id
        if traffic.active:
            data['active'] = 1
        else:
            data['active'] = 0
        
        data['position_name'] = traffic.position.name
        data['position_size'] = position_size_to_str(traffic.position.width, traffic.position.height)
        data['width'] = traffic.position.width
        data['height'] = traffic.position.height
        data['max']=traffic.position.max
        data['position_attrs'] = [attr.name for attr in traffic.position.attrs.all()]
        data['media_name'] = traffic.position.media.name
        data['media_attrs'] = [ attr.name for attr in traffic.position.media.attrs.all()]
        data['start'] = traffic.start.strftime("%Y-%m-%d")
        data['end'] = traffic.end.strftime("%Y-%m-%d")
        data['bid_type'] = traffic_bid_type(traffic.bid_type)
        data['bid_price'] = traffic.bid_price
        data['pv'] = traffic.estimated_imp
        data['click'] = traffic.estimated_click
        data["can_deleted"]=traffic.end >today()     
        resource=Resource.objects.filter(traffic_id=traffic.id,allow_shared=True)
        if not resource:
            data['shared']= "平台"
            data['floor']=0
        else:
            data['shared']="竞价" 
            data['floor']=resource[0].floor                   
        datalist.append(data)
    return datalist

# traffic 列表构造json,平台流量使用者
def traffic_platform_to_json(list):
    datalist = []
    for traffic in list:
        data = {}
        data['traffic_id'] = traffic.id
        data['position_name'] = traffic.position.name
        data['position_attrs'] = position_attrs_to_str(traffic.position.attrs.all())
        data['media_name'] = traffic.position.media.name
        data['media_attrs'] = [attr.name for attr in traffic.position.media.attrs.all()]
        data["width"]=traffic.position.width
        data["height"]=traffic.position.height
        data["max"]=traffic.position.max
        data['start'] = traffic.start.strftime("%Y-%m-%d")
        data['end'] = traffic.end.strftime("%Y-%m-%d")
        data['pv'] = traffic.estimated_imp
        data['click'] = traffic.estimated_click
        data["can_deleted"]=traffic.end>today()
       
        resource=Resource.objects.filter(traffic_id=traffic.id,allow_shared=True)
        if not resource:
            data['shared']= "平台"            
        else:
            data['shared']="竞价" 
        data["material"]=0
        default_strategy=get_default_traffic_strategy({"tid":traffic.id})
        if default_strategy:
            if default_strategy.materialweight_set.all().exists():
                data["material"]=1                             
        datalist.append(data)
    return datalist

# traffic 列表构造json,平台流量使用者
def traffic_shop_to_json(list):
    datalist = []
    for traffic in list:
        data = {}
        data['traffic_id'] = traffic.id
        data['position_width'] = traffic.position.width
        data['position_height'] = traffic.position.height
        data['position_name'] = traffic.position.name
        data["width"]=traffic.position.width
        data["height"]=traffic.position.height
        data["max"]=traffic.position.max
        data['position_attrs'] = position_attrs_to_str(traffic.position.attrs.all())
        data['media_name'] = traffic.position.media.name
        data['media_attrs'] = [ attr.name for attr in traffic.position.media.attrs.all()]
        data['start'] = traffic.start.strftime("%Y-%m-%d")
        data['end'] = traffic.end.strftime("%Y-%m-%d")
        data['pv'] = traffic.estimated_imp
        data['click'] = traffic.estimated_click
        data["can_deleted"]=traffic.end>today()
        resource=Resource.objects.filter(traffic_id=traffic.id,allow_shared=True)
        if not resource:            
            data['floor']=0
        else:           
            data['floor']=resource[0].floor          
        datalist.append(data)
    return datalist
#role 为角色，1：admin，2：platform，3：vendor or merchant
#type 1:CPM,0:CPD
def traffic_reports_to_json(reports,traffic,role,start,end):
    if start >end :
        start,end = end,start
    datalist = []
    data_by_day={}
    for report in reports:
        print report
        data_by_day[report.date]=(report.pv,report.uv,report.click,report.cost)

    date_region=date_region_intersect(traffic.start, traffic.end, start, end)
    date_arr = date_range_array(start, end);
    cost_report = dict((d,0) for d in date_arr or [])
    if date_region :
        min_date = date_region[0]
        max_date = date_region[1]
        while min_date<=max_date :
#             0 CPD  1 CPM
            if traffic.bid_type==0:
                cost_report[min_date] += traffic.bid_price
            elif traffic.bid_type==1:
                cost_report[min_date] +=traffic.bid_price *data_by_day.get(min_date,(0,0,0,0))[0]*1.0/1000
            min_date+=datetime.timedelta(days=1)


    for d in date_arr :
        data = {}
        if role==1 or role ==2:
            data['cost'] = cost_report[d]
            data['bid'] = data_by_day.get(d,(0,0,0,0))[3]
        elif  role==3:
            data['cost'] = data_by_day.get(d,(0,0,0,0))[3]
        data['pv']= data_by_day.get(d,(0,0,0,0))[0]
        data['uv'] = data_by_day.get(d,(0,0,0,0))[1]
        data['click'] = data_by_day.get(d,(0,0,0,0))[2]
        data['ctr'] = 0
        if data['pv'] != 0 :
            data["ctr"] = data['click']*1.0/data["pv"]
        data['date'] = d
        data["sale_income"]=get_cost_by_traffic(d,traffic.id)
        data["profit"]=data["bid"]+data["sale_income"]-data["cost"]
        datalist.append(data)
    return datalist

##########################################################

def is_traffic_shared(tid):
    resource=Resource.objects.filter(traffic_id=tid,allow_shared=True)
    if not resource:
        return "平台"
    else:
        return "竞价"
    
    
def get_traffic_floor(tid):
    resource=Resource.objects.get(traffic_id=tid,allow_shared=True)
    if resource.RESOURCE.all().exists():
        floor=0
    else:
        floor=resource.floor
    return floor
    
